//
//  AppService.m
//  BHGY
//
//  Created by liuxiang on 2020/7/3.
//  Copyright © 2020 liuxiang. All rights reserved.
//

#import "AppService.h"
#import "WMDragView.h"

BOOL isCurrentTimeInWeekdayTimeRange() {
    // 创建当前日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 获取当前日期和时间
    NSDate *now = [NSDate date];
    // 获取当前日期的小时和分钟以及星期几
    NSDateComponents *nowComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitWeekday) fromDate:now];
    // 判断是否在周一到周五
    if (nowComponents.weekday < 2 || nowComponents.weekday > 6) {
        return NO; // 周日或周六，不在范围内
    }
    // 定义时间段
    NSArray<NSArray<NSNumber *> *> *timeRanges = @[
        @[@9, @20], // 9:20
        @[@11, @30], // 11:30
        @[@13, @0], // 13:00
        @[@15, @0] // 15:00
    ];
    
    // 遍历时间段，检查当前时间是否在某个时间段内
    for (int i = 0; i < timeRanges.count; i += 2) {
        NSArray<NSNumber *> *start = timeRanges[i];
        NSArray<NSNumber *> *end = timeRanges[i + 1];
        
        NSInteger startHour = [start[0] integerValue];
        NSInteger startMinute = [start[1] integerValue];
        NSInteger endHour = [end[0] integerValue];
        NSInteger endMinute = [end[1] integerValue];
        
        // 如果当前时间在开始时间之后且在结束时间之前，则返回YES
        if ((nowComponents.hour > startHour || (nowComponents.hour == startHour && nowComponents.minute >= startMinute)) &&
            (nowComponents.hour < endHour || (nowComponents.hour == endHour && nowComponents.minute < endMinute))) {
            return YES;
        }
    }
    
    // 如果没有找到匹配的时间段，则返回NO
    return NO;
}

@interface AppService ()<XTWebSocketDelegate>
@property(nonatomic,copy)NSString *stocksCode;
@property(nonatomic,strong)dispatch_source_t timer;
@property(nonatomic,strong)dispatch_queue_t queue;

@end

@implementation AppService
//单例
+ (instancetype)shareInstance
{
    static AppService *_instace = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        _instace = [[self alloc] init];
    });
    return _instace;
}


- (instancetype)init
{
    self = [super init];
    if(self)
    {
        
        self.queue = dispatch_queue_create("com.stock.syncQueue", DISPATCH_QUEUE_SERIAL);
        self.weather = @"--";
        
        self.webSocket = [[XTWebSocket alloc] initWithServerIp:@"ws://124.222.224.186:8800"];
        self.webSocket.delegate = self;
        //        [self.webSocket connectWebSocket];
        [self loadcodes];
        [self startTimer];
        
    }
    return self;
}

- (void)creatDragView{
    WMDragView *dragView = [[WMDragView alloc] init];
    dragView.backgroundColor = Color_Theme;
    dragView.frame = CGRectMake(20, 300, 50, 50);
    dragView.isKeepBounds = YES;
    dragView.dragEnable = YES;
    dragView.freeRect = CGRectMake(0, Height_NavBar, kScreenWidth, kScreenHeight - Height_NavBar - Height_TabBar);
    [[UIApplication sharedApplication].delegate.window addSubview:dragView];
}

- (void)loadcodes{
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [NSString stringWithFormat:@"%@/allcodes",MYSTOCKUrl];
    entity.needCache = NO;
    entity.parameters = nil;
    
    [BANetManager ba_request_GETWithEntity:entity successBlock:^(id response) {
        NSDictionary *result = response;
        if ([result[@"code"] intValue] == 1) {
            self.stocksCode = result[@"data"];
            [self startTimer];
        }
        
    } failureBlock:^(NSError *error) {
        
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        
    }];
}


- (void)startTimer{
    //0.创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 15 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //3.要调用的任务
    dispatch_source_set_event_handler(self.timer, ^{
        //         [self loadStockData];
        //         if (isCurrentTimeInWeekdayTimeRange()) {
        [self startRequest];
        [self timerLoadWeather];
        //             NSLog(@"在时间段内部段的去请求");
        //         }
        
    });
    
    //4.开始执行
    dispatch_resume(self.timer);
}

- (void)timerLoadWeather{
    dispatch_async(self.queue, ^{
        // 追加任务 1
        [self loadWeather];
    });
}

- (void)loadWeather{
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [NSString stringWithFormat:@"%@/hotgl",MYSTOCKUrl];
    entity.needCache = NO;
    entity.parameters = nil;
    
    [BANetManager ba_timer_request_GETWithEntity:entity successBlock:^(id response) {
        NSDictionary *result = response;
        if ([result[@"code"] intValue] == 1) {
            NSString *weatherStr = result[@"data"][@"datas"][@"weather"];
            if(![self.weather isEqualToString:weatherStr]){
                [[NSNotificationCenter defaultCenter] xw_postNotificationWithName:@"weather" userInfo:@{@"weather":weatherStr}];
            }
            self.weather = weatherStr;
        }
        
    } failureBlock:^(NSError *error) {
        
        
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        
    }];
}

- (void)startRequest{
    
    
    NSArray *array = [self.stocksCode componentsSeparatedByString:@","];
    for (NSString *code in array) {
        dispatch_async(self.queue, ^{
            [self loadDataWithStockCode:code];
        });
    }
    
    
    
}

- (void)loadDataWithStockCode:(NSString *)code{
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [NSString stringWithFormat:@"%@?%@",KPUrl,[NSString stringWithFormat:@"PhoneOSNew=2&StockID=%@&UserID=2429689&VerSion=5.16.0.5&a=GetStockPanKou_Narrow&apiv=w38&c=StockL2Data",code]];
    
    entity.needCache = NO;
    entity.parameters = nil;
    //主力净额 6
    [BANetManager ba_timer_request_POSTWithEntity:entity successBlock:^(id response) {
        NSDictionary *result = response;
        if ([result[@"errcode"] intValue] == 0) {
            
            NSDictionary *stockData = result[@"real"];
            NSMutableDictionary *mStockData = [NSMutableDictionary dictionaryWithDictionary:stockData];
            mStockData[@"scode"] = result[@"code"];
            [[NSNotificationCenter defaultCenter] xw_postNotificationWithName:result[@"code"] userInfo:mStockData];
        }
    } failureBlock:^(NSError *error) {
        
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        
    }];
    
    
}


- (void)loadStockData{
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [NSString stringWithFormat:@"%@?%@",KPUrl,[NSString stringWithFormat:@"DeviceID=436b0b6010b384e985b1e54b0b2ae53ee51282bb&PhoneOSNew=2&StockIDList=%@&Token=9a2684ea1c27da404bf2e5a8253bc7cf&UserID=2429689&VerSion=5.16.0.1&a=RefreshStockList&apiv=w38&c=UserSelectStock",self.stocksCode]];
    
    entity.needCache = NO;
    entity.parameters = nil;
    //主力净额 6
    
    [BANetManager ba_request_GETWithEntity:entity successBlock:^(id response) {
        NSDictionary *result = response;
        if ([result[@"errcode"] intValue] == 0) {
            
            NSArray *stockList = result[@"StockList"];
            for (NSDictionary *stockInfo in stockList) {
                [[NSNotificationCenter defaultCenter] xw_postNotificationWithName:stockInfo[@"StockID"] userInfo:stockInfo];
            }
            
            
        }
    } failureBlock:^(NSError *error) {
        
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        
    }];
}

- (void)xtWebSocketDidReceiveMessage:(NSString *)message{
    
    //    NSLog(@"======%@",message);
    
}

- (void)registerAppService:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    [self handleKeyBoard];
    //    [self upDateLastOnline];
    [self handleNetwork];
    
    
}

- (void)handleNetwork{
    [[BANetManager sharedBANetManager] setTimeoutInterval:15];
}

- (void)upDateLastOnline{
    
    
    
}

- (void)handleKeyBoard{
    //键盘处理
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
    
    
    // wrnavgation
    [WRNavigationBar wr_widely];
    [WRNavigationBar wr_setBlacklist:@[@"TZImgePickHelper",@"TZImagePickerController",
                                       @"TZPhotoPickerController",
                                       @"TZGifPhotoPreviewController",
                                       @"TZAlbumPickerController",
                                       @"TZPhotoPreviewController",
                                       @"TZVideoPlayerController",@"RCConversationViewController",@"ChatVC"]];
    //
    
    
    
    //    [WRNavigationBar wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
    //    [WRNavigationBar wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
    //    [WRNavigationBar wr_setDefaultNavBarBarTintColor:Color_Theme];
    
    
    
    
    //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:Color_Theme] forBarMetrics:UIBarMetricsDefault];
    
    
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithColor:Color_Theme] forBarMetrics:UIBarMetricsDefault];
    
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],
                                                           NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"]}];
    
    //    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(2, 1)
    //                                                            forBarMetrics:UIBarMetricsDefault];
    //       UIImage *tmpImage = [UIImage imageNamed:@"fanhui"];
    //       CGSize newSize = CGSizeMake(10, 17);
    //       UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0f);
    //       [tmpImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    //       UIImage *backButtonImage = UIGraphicsGetImageFromCurrentImageContext();
    //       UIGraphicsEndImageContext();
    //       [[UINavigationBar appearance] setBackIndicatorImage:backButtonImage];
    //       [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:backButtonImage];
    //
    //    [UINavigationBar appearance].translucent = NO;
    //
    
    
    //   UIImage *backButtonImage = [[UIImage imageNamed:@"fanhui"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
    //   [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    //将返回按钮的文字position设置不在屏幕上显示
    //   [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
}



@end

